package com.qiguliuxing.dts.core.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

	private static final int CORS_FILTER_BEAN_ORDER = 1; // 跨域过滤器bean 优先级

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
		corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
		corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
		corsConfiguration.setAllowCredentials(true);
		return corsConfiguration;
	}

    /*@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
		return new CorsFilter(source);
	}*/

	/**
	 * 替换升级后的跨域配置，否则报 Redirect is not allowed for a preflight request错误
	 * 调整CORS Filter优先级，让其先于登录验证
	 * @return
	 */
	@Bean
	public FilterRegistrationBean corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // CORS 配置对所有接口都有效
		FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
		bean.setOrder(CORS_FILTER_BEAN_ORDER);
		return bean;
	}
}
